-----------------------------------------------------------------------------
-- 副官设置界面（更换设置界面的立绘）
--
---------------
-- Author: wd
-----------------------------------------------------------------------------
require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UISelectShow = {};
HelperFunc.SetUIEnv(UISelectShow)
local this = UISelectShow;

this.hasInit = false;
this.heroConfig = nil;
this.heroDataList = {}
this.curSelectIndex = nil
this.lastSelectIndex = nil
this.lastObj = nil
this.selectHeroID = nil

--- 主城背景数据结构
--- @alias BgItemStruct {id: number, name: string, imgUrl: string}

--- 主城背景数据集合
--- @type BgItemStruct[]
this.bgItemDatas = nil

local selectedBgIndex = nil
local selectedBgItem  = nil

function UISelectShow.Init()
    if heroConfig == nil then
        heroConfig = G.dataTable["t_hero"];
    end

    local name, packageName = getUIName(PanelResNames.UISelectShow);
    panelMgr:ShowUI(name, packageName, this.OnCreate, Config.useLocalUI);
end

function UISelectShow.OnCreate(obj)
    if not hasInit then
        hasInit = true;

        this.bind = {
            comSelectHero = obj:GetChild("ComSeleHero"),
        }
        this.bind.btnClose = this.bind.comSelectHero:GetChild("btnClose")
        this.bind.btnBack = this.bind.comSelectHero:GetChild("BackBtn")
        this.bind.ctrlTab = this.bind.comSelectHero:GetController("ctrlTab")
        this.bind.listHero = this.bind.comSelectHero:GetChild("itemGrid")
        this.bind.btnSure = this.bind.comSelectHero:GetChild("btnSure")
        this.bind.listBg = this.bind.comSelectHero:GetChild("list_bg")
        this.bind.btnHero = this.bind.comSelectHero:GetChild("btnHero")
        this.bind.btnBg = this.bind.comSelectHero:GetChild("btnBg")
        this.bind.ctrlMode = this.bind.comSelectHero:GetController("ctrlMode")
        
        this.bind.listHero.itemRenderer = this.UpdateOneElement
        this.bind.listBg.itemRenderer = this.backgroundItemRenderer
        this.addEvent()
    end

    this.currHeroId = logicMgr.HeroManager.GetRoleHeadID()

    this.bind.ctrlTab.selectedIndex = EnumConst.HeroTypeEnum.HeroTypeAll
    this.RefreshPage()
    this.initBackgroundData()
    this.refreshBackgroundView()
end

function UISelectShow.InitlizeData()
    if lastObj then
        local tmpCtr = lastObj:GetController("gou")
        tmpCtr.selectedIndex = 0
    end
    curSelectIndex = nil
    lastSelectIndex = nil
    lastObj = nil
end

function UISelectShow.UpdateOneElement(index, obj)
    index = index + 1
    local heroInfo = heroDataList[index]
    local itemValue = {};
    itemValue["partnerModelId"] = heroInfo.f_HeroID
    itemValue["star"] = heroInfo.f_HeroInitialStar;
    itemValue["type"] = heroInfo.f_HeroType;
    itemValue["skinId"] = heroInfo.skinId;
    local HeadRectDrawItem = CtrlManager.GetCtrl(PanelNames.HeadRectDrawItem);
    if HeadRectDrawItem ~= nil then
        HeadRectDrawItem.initData(obj, itemValue);
    end
    -- 事件侦听
    obj.onClick:Clear()
    obj.onClick:Add(function()
        this.OnClickHeroPos(heroInfo.f_HeroID, index, obj)
    end)

    -- 默认选中
    if this.currHeroId and this.currHeroId == heroInfo.f_HeroID then
        local ctrlGou = obj:GetController("gou")
        ctrlGou.selectedIndex = 1
        lastObj = obj
        lastSelectIndex = index
    end
end

function UISelectShow.OnClickHeroPos(heroID, index, obj)
    curSelectIndex = index
    if lastSelectIndex ~= curSelectIndex then
        if lastObj then
            local tmpCtr = lastObj:GetController("gou")
            tmpCtr.selectedIndex = 0
        end
        lastObj = obj
        lastSelectIndex = curSelectIndex

        local ctrlGou = obj:GetController("gou")
        ctrlGou.selectedIndex = 1
        if heroID then
            selectHeroID = heroID
            FireEvent(Config.EventType.FreashSettingDraw, heroID)
        end
    end
end

function UISelectShow.RefreshPage()
    this.InitlizeData()

    local index = this.bind.ctrlTab.selectedIndex
    table.clear(heroDataList)
    for _, value in pairs(heroConfig) do
        local schoolLimit = (value.f_HeroType == index)
        if index == EnumConst.HeroTypeEnum.HeroTypeAll then
            schoolLimit = true
        end
        if schoolLimit and logicMgr.HeroManager.getHandbookByModelId(tostring(value.f_HeroID),true) then
            if logicMgr.HeroManager.isOpenHeroAtlas(value.f_HeroID) then
                table.insert(heroDataList,value);
            end
        end
    end
    --this.itemPoolMgr:ReturnUsedToPool()
    logicMgr.HeroManager.SetMyHeroSkin(heroDataList)
    table.sort(heroDataList,function (a,b)
        if a.f_HeroInitialStar~= b.f_HeroInitialStar then
            return a.f_HeroInitialStar>b.f_HeroInitialStar;
        end
        return a.f_HeroID< b.f_HeroID;
    end);

    this.bind.listHero.numItems = #heroDataList
end

----------------------------------------------------------------------
--- 主城背景
----------------------------------------------------------------------
function UISelectShow.initBackgroundData()
    this.bgItemDatas = {}

    local tableData = dataTable.getDataTable("t_citybg")
    for key, data in pairs(tableData) do
        --- @type BgItemStruct
        local itemData = {
            id     = data.f_CityBgId,
            name   = data.f_CityBgName,
            imgUrl = data.f_BgImgUp
        }
        table.insert(this.bgItemDatas, itemData)
    end

    table.sort(this.bgItemDatas, function(v1, v2) 
        return v1.id < v2.id
    end)
end
function UISelectShow.refreshBackgroundView()
    this.bind.listBg.numItems = #this.bgItemDatas

    local isOpen = logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CityBackground, false)
    local ctrlLock = this.bind.btnBg:GetController("lock")
    ctrlLock.selectedIndex = not isOpen and 1 or 0
end
function UISelectShow.backgroundItemRenderer(index, obj)
    local ctrlSelect = obj:GetController("select")
    local imgBg      = obj:GetChild("n1"):GetChild("n1")
    local txtName    = obj:GetChild("n3")

    -- 背景数据
    local data = this.bgItemDatas[index + 1]
    imgBg.url  = data.imgUrl
    txtName.text = getLanguage(data.name)

    -- 当前所用背景
    local currId = HeroManager.getCityBackground()
    if currId == data.id then
        selectedBgIndex = index
        selectedBgItem  = obj
        ctrlSelect.selectedIndex = 1
    end

    -- 事件侦听
    obj.onClick:Clear()
    obj.onClick:Add(function()
        this.onClickBackgroundItem(index, obj, data.id)
    end)
end
function UISelectShow.onClickBackgroundItem(index, obj, bgId)
    if selectedBgIndex == index then
        return
    end

    if selectedBgItem then
        selectedBgItem:GetController("select").selectedIndex = 0
    end
    obj:GetController("select").selectedIndex = 1
    selectedBgIndex = index
    selectedBgItem  = obj

    FireEvent(Config.EventType.FreashCityBackground, bgId)
end

function UISelectShow.UpdateTab(index, obj)
    obj.onClick:Add(function()
        this.SelectSchoolTab(index, obj)
    end)
end

function UISelectShow.addEvent()
    this.bind.btnBack.onClick:Add(this.OnClickBack)
    this.bind.btnClose.onClick:Add(this.OnClickBack)
    this.bind.btnSure.onClick:Add(this.OnClickSure)
    this.bind.ctrlTab.onChanged:Add(this.OnTabChanged)
    this.bind.btnHero.onClick:Add(this.onClickHero)
    this.bind.btnBg.onClick:Add(this.onClickBg)
end

function UISelectShow.removeEvent()
    this.bind.btnBack.onClick:Clear()
    this.bind.btnBack.onClick:Clear()
    this.bind.ctrlTab.onChanged:Clear()
    this.bind.ctrlTab.onChanged:Clear()
    this.bind.btnHero.onClick:Clear()
    this.bind.btnBg.onClick:Clear()
end

function UISelectShow.OnTabChanged()
    this.RefreshPage();
end

function UISelectShow.LocalListenEvent()

end

function UISelectShow.LocalCloseEvent()

end

function UISelectShow.OnDestroy()
    selectedBgIndex  = nil
    selectedBgItem   = nil
    this.bgItemDatas = nil

    this.removeEvent();
end

function UISelectShow.OnEnable()
    this.LocalListenEvent();
end

function UISelectShow.OnDisable()
    this.LocalCloseEvent();
end

function UISelectShow.onClickHero()
    if this.bind.ctrlMode.selectedIndex == 0 then
        return
    end
    this.bind.ctrlMode.selectedIndex = 0
    this.bind.btnHero.selected = true
    this.bind.btnBg.selected = false
end
function UISelectShow.onClickBg()
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CityBackground, true, this.bind.btnBg) then
        return
    end
    if this.bind.ctrlMode.selectedIndex == 1 then
        return
    end
    this.bind.ctrlMode.selectedIndex = 1
    this.bind.btnHero.selected = false
    this.bind.btnBg.selected = true
end

function UISelectShow.OnClickSure()
    if curSelectIndex ~= nil then
        local heroInfo = heroDataList[curSelectIndex]
        if heroInfo then
            selectHeroID = heroInfo.f_HeroID
            local skinId = tostring(logicMgr.SkinManager.getHeroSkinId(selectHeroID))
            roleInfoHandler.SendReqModifyPicMessage(skinId)
            this.OnClickBack()
        end
    else
        UISysTips.AddMsg("请选择你心仪的指挥官")
    end
end

function UISelectShow.OnClickBack()
    -- 取消确认选择操作，此处逻辑无效
    -- if selectHeroID and selectHeroID ~= logicMgr.HeroManager.GetRoleHeadID() then
    --     local heroModelId = logicMgr.SkinManager.getHeroModelIdBySkinId(logicMgr.HeroManager.GetRoleInfo("pic"))
    --     FireEvent(Config.EventType.FreashRoleShowDraw, heroModelId)
    -- end
    this.backSave()

    closeUI(PanelNames.UISelectShow);
end

--- 新增返回保存
function UISelectShow.backSave()
    -- 立绘
    if curSelectIndex ~= nil then
        local heroInfo = heroDataList[curSelectIndex]
        if heroInfo then
            selectHeroID = heroInfo.f_HeroID
            local skinId = tostring(logicMgr.SkinManager.getHeroSkinId(selectHeroID))
            roleInfoHandler.SendReqModifyPicMessage(skinId)
        end
    end

    -- 主城背景
    if selectedBgIndex then
        local currId = HeroManager.getCityBackground()
        local bgId   = this.bgItemDatas[selectedBgIndex + 1].id
        if currId ~= bgId then
            roleInfoHandler.ReqReplaceCityBackground(bgId)
        end
    end
end

return UISelectShow;
